package atm.service.impl;

import atm.dao.UserDAO;
import atm.dao.impl.UserDAOImpl;
import atm.pojo.UserDO;
import atm.service.UserService;

import javax.swing.*;

public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();

    @Override
    public UserDO getBYUsernameAndPwd(String username, String pwd) {
        return userDAO.getBYUsernameAndPwd(username, pwd);
    }

    @Override
    public void saveMoney(int id, double blance) {
        UserDO user = userDAO.getById(id);
        user.setMoney(user.getMoney() + blance);
        userDAO.update(user);
    }

    @Override
    public void drawMoney(int id, double blance) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getMoney() < blance) {
            throw new Exception("余额不足");
        }
        user.setMoney(user.getMoney() - blance);
        userDAO.update(user);
    }

    @Override
    public void change(int id, String oldpwd, String newpwd) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getPassword().equals(oldpwd)) {
            user.setPassword(newpwd);
            userDAO.update(user);
        } else {
            throw new Exception("与旧密码密码不匹配");
        }
    }

    @Override
    public void transform(int id, String othername, double money) throws Exception {
        UserDO loginuser = userDAO.getById(id);
        UserDO otheruser = userDAO.getByUsername(othername);
        if (otheruser == null) {
            throw new Exception("查无此人");
        }
        if (loginuser.getAccount().equals(othername)) {
            throw new Exception("不能给自己转账");
        }
        if (money > loginuser.getMoney()) {
            throw new Exception("余额不足");
        }
        loginuser.setMoney(loginuser.getMoney() - money);
        userDAO.update(loginuser);
        otheruser.setMoney(otheruser.getMoney() + money);
        userDAO.update(otheruser);


    }


}
